<template>
  <div>
    <div class="blocklyDiv" ref="blocklyDiv"></div>
    <xml ref="blocklyToolbox" style="display: none">
      <slot></slot>
    </xml>
  </div>
</template>

<script>
import Blockly from 'blockly'
import * as Ch from 'blockly/msg/zh-hans'
import EventBus from '@/utils/eventBus'
import Theme from '../theme/index.js'
import builtInParam from '../utils/builtInParam'
Blockly.setLocale(Ch)
export default {
  name: 'BlocklyComponent',
  props: ['options', 'eventItem'],
  data () {
    return {
      workspace: null
    }
  },
  mounted () {
    var options = this.$props.options || {}
    const that = this
    options.theme = Theme
    if (!options.toolbox) {
      options.toolbox = this.$refs['blocklyToolbox']
    }
    this.workspace = Blockly.inject(this.$refs['blocklyDiv'], options)
    // 第一次进页面右键菜单不要撤销的选项
    setTimeout(() => {
      this.workspace.undoStack_ = []
      // 与rightModel通信worksoace
      EventBus.$emit('sendWorkspace', this.workspace)
      // const root = this.workspace.getBlockById('rootBlock')
      const root = this.workspace.getBlocksByType('root_function_expression')[0]
      root && (root.composeKey = this.eventItem?.composerKey)
    }, 500)
    // 监听不同类型的积木
    function onClickBlock (event) {
      // todo 2022-02-11 17:58:13 add click
      const eventTypeArr = ['ui', 'change', 'click']
      const blocks = that?.workspace?.getAllBlocks() || []
      console.log('event.type', event.type, event.blockId, event)

      if (
        (event.type === 'ui' &&
          event.element === 'click' &&
          event.newValue === 'workspace') ||
        (event.type === 'click' && event.targetType === 'workspace')
      ) {
        // 点击空白区域显示全局配置
        blocks.forEach((item) => delete item.isClicked)
        that.$emit('setShowGlobal')
      } else if (eventTypeArr.includes(event.type)) {
        if (!event.blockId || !that.workspace) return
        const block = that.workspace.getBlockById(event.blockId)
        blocks.forEach((item) => delete item.isClicked)
        block.isClicked = true
        // if (
        //   block.type === 'callback_function_expression' &&
        //   event.element === 'dragStart'
        // ) { return }
        if (block.type === 'params_input') return
        that.$emit('setRightModelBlock', block)
      } else if (event.type === 'move') {
        if (!event.blockId || !that.workspace) return
        const block = that.workspace.getBlockById(event.blockId)
        if (block?.type === 'params_input') {
          if (event?.newParentId) {
            const parent = that.workspace.getBlockById(event?.newParentId)
            if (parent.type === 'variables_set') {
              const connection = parent.getInput(`VALUE`).connection
              connection.disconnect()
            }
          }
        }
        if (block?.type === 'callback_function_expression') {
          that.$emit('setRightModelBlock', block)
        }
      }
    }

    this.workspace.addChangeListener(onClickBlock)

    this.workspace.registerToolboxCategoryCallback(
      'BUILTIN_PARAM_PALETTE',
      Blockly.builtInParam.flyoutCategory
    )
  },
  methods: {
    saveWorkspace () {
      let hasErrorBlock = false
      var topBlocks = this.workspace.getTopBlocks()
      if (topBlocks.length > 1) {
        hasErrorBlock = topBlocks.some(
          (item) =>
            item.type !== 'root_function_expression' &&
            item.type !== 'procedures_defnoreturn' &&
            item.type !== 'procedures_defreturn'
        )
        if (hasErrorBlock) {
          this.$message.warning('顶级块只能是事件或函数')
        }
      }
      return !hasErrorBlock
    }
  }
}
</script>

<style scoped>
.blocklyDiv {
  height: 100%;
  width: 100%;
  text-align: left;
}
</style>
